//
//  ISSafetyAlarmCameraManager.m
//  iPhoneSafety
//
//  Created by dl on 2019/1/4.
//  Copyright © 2019 com.li.ding. All rights reserved.
//

#import "ISSafetyAlarmCameraManager.h"
#import <AVFoundation/AVFoundation.h>

@interface ISSafetyAlarmCameraManager()
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput;
@end

@implementation ISSafetyAlarmCameraManager

NW_SINGLETON_INSTANCE_METHOD_IMPLEMENTATION

- (instancetype)init {
    self = [super init];
    if (self) {
        self.captureSession = [[AVCaptureSession alloc]init];
        self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
        
        NSError *error = nil;
        AVCaptureDevice *captureDevice = [self frontCameraDevice];
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
        [self.captureSession addInput:input];
        
        self.stillImageOutput = [AVCaptureStillImageOutput new];
        self.stillImageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
        [self.captureSession addOutput:self.stillImageOutput];
    }
    return self;
}

- (void) takePhotoWithCompletion:(void(^)(UIImage *image))completion {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status != AVAuthorizationStatusAuthorized) {
        !completion ?: completion(nil);
        return ;
    }
    [self.captureSession startRunning];
    
    AVCaptureConnection *conn = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    @weakify(self)
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:conn completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
        @strongify(self)
        if (!CMSampleBufferIsValid(imageDataSampleBuffer)) {
            dispatch_async(dispatch_get_main_queue(), ^{
                !completion ?: completion(nil);
            });
        } else {
            NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:data];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                !completion ?: completion(image);
            });
        }
        [self.captureSession stopRunning];
    }];
}

- (AVCaptureDevice *) frontCameraDevice {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == AVCaptureDevicePositionFront) {
            return device;
        }
    }
    return nil;
}

@end
